package com.donger.auth.validate;

import cn.hutool.core.util.StrUtil;
import com.donger.auth.exception.ValidateCodeException;
import com.donger.common.core.constant.CommonConstants;
import com.donger.common.core.constant.SecurityConstants;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * @author aeizzz
 * 检验短信验证码
 */
@Slf4j
@AllArgsConstructor
@Component(value = SecurityConstants.DEFAULT_PARAMETER_NAME_CODE_SMS)
public class SmsValidateCodeProcessor implements ValidateCodeProcessor {


    private final RedisTemplate redisTemplate;

    @Override
    public void validate(HttpServletRequest request) {
        log.info("校验短信验证码 -> {}", request.getRequestURI());
        String code = request.getParameter("code");

        String mobile = request.getParameter("mobile");

        String randomStr = null;
        if (StrUtil.isNotBlank(mobile)) {
            String[] split = mobile.split("@");
            randomStr = split[1];
        }

        Object codeObj = redisTemplate.opsForValue().get(CommonConstants.DEFAULT_PHONE_KEY + randomStr);

        if (codeObj == null) {
            throw new ValidateCodeException("验证码已过期");
        }
        if (StrUtil.isBlank(code)) {
            throw new ValidateCodeException("请输入验证码");
        }
        if (!code.equals(codeObj)) {
            throw new ValidateCodeException("请输入正确的验证码");
        }
        // 成功以后删除验证码
        redisTemplate.delete(CommonConstants.DEFAULT_PHONE_KEY + randomStr);
    }
}
